<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="R language learning Notes, 这里是网站关键词">
    <meta name="description" content="这里是网站描述">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="baidu-site-verification" content="code-8VjAnGhv8m" />
    <meta name="google-site-verification" content="An02eAw6rCWBVutF85tRr02GvZox5D4Pqd9PKFRzvBs" />
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>R language learning Notes | Oliver博客</title>
    
    <script>
        // 隐藏
        //右键
        // document.oncontextmenu = function (event){
        //     if(window.event){
        //     event = window.event;
        //     }try{
        //     var the = event.srcElement;
        //     if (!((the.tagName == "INPUT" && the.type.toLowerCase() == "text") || the.tagName == "TEXTAREA")){
        //     return false;
        //     }
        //     return true;
        //     }catch (e){
        //     return false;
        //     }
        // }

        //debugger部分
            // setInterval(function() {
            // check();
            // }, 500);
            // var check = function() {
            //     function doCheck(a) {
            //     if (('' + a / a)['length'] !== 1 || a % 20 === 0) {
            //         (function() {}['constructor']('debugger')());
            //     } else {
            //         (function() {}['constructor']('debugger')());
            //     }
            //     doCheck(++a);
            //     }
            //     try {
            //     doCheck(0);
            //     } catch (err) {}
            // };
            // check();

            // ctrl+s保存
            // document.onkeydown = function() {
            //     if ((e.ctrlKey) && (e.keyCode == 83)) { //ctrl+s
            //         return false;
            //     }
            // }
            // window.addEventListener("keydown", function(e) {
            //     //可以判断是不是mac，如果是mac,ctrl变为花键
            //     //event.preventDefault() 方法阻止元素发生默认的行为。
            //     if((e.key=='s'||e.key=='S')&&(navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)){
            //         e.preventDefault();
            //     }
            // }, false);
            // F12
            // document.onkeydown = function(){
            //     if(window.event && window.event.keyCode == 123) {
            //         event.keyCode=0;
            //         event.returnValue=false;
            //     }
            //     if(window.event && window.event.keyCode == 13) {
            //         window.event.keyCode = 505;
            //     }
            //     if(window.event && window.event.keyCode == 8) {
            //         window.event.returnValue=false;
            //     }
            // }
        //宽高
        // var threshold = 160; // 打开控制台的宽或高阈值  
        // // 每秒检查一次  
        // window.setInterval(function() {  
        //     if (window.outerWidth - window.innerWidth > threshold ||   
        //     window.outerHeight - window.innerHeight > threshold) {  
        //         // 如果打开控制台，则刷新页面  
        //         window.location.reload();  
        //     }  
        // }, 1e3);

        //debug调试时跳转页面
        // var element = new Image();
        // Object.defineProperty(element,'id',{get:function(){window.location.href="/tenfour/homepage/"}});
        // console.log(element);
    </script>
    
    <link rel="icon" type="image/png" href="/medias/favicon.webp">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">
    <link type='text/css' rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css"/>
    
    <script src="/libs/jquery/jquery.min.js"></script>
    <!-- <script src="/js/foropensource.js"></script> -->
    <script>
        (function(){
            var bp = document.createElement('script');
            var curProtocol = window.location.protocol.split(':')[0];
            if (curProtocol === 'https'){
           bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
          }
          else{
          bp.src = 'http://push.zhanzhang.baidu.com/push.js';
          }
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(bp, s);
        })();
    </script>
<!-- hexo injector head_end start -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.css">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hexo-math@4.0.0/dist/style.css">
<!-- hexo injector head_end end --><meta name="generator" content="Hexo 5.0.2"><link rel="alternate" href="/atom.xml" title="Oliver博客" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>

<!-- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.css" integrity="sha384-bsHo4/LA+lkZv61JspMDQB9QP1TtO4IgOf2yYS+J6VdAYLVyx1c3XKcsHh0Vy8Ws" crossorigin="anonymous">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.js" integrity="sha384-4z8mjH4yIpuK9dIQGR1JwbrfYsStrNK6MP+2Enhue4eyo0XlBDXOIPc8b6ZU0ajz" crossorigin="anonymous"></script> -->
<!-- 提示：若要开启春节或者圣诞主题样式，直接给body标签添加一个class为
class="themespring" -->
<body>
    <!-- 网站全局深色模式设置开始 -->
    <script>
        if (localStorage.getItem('dark') === '1') {
        document.body.classList.add('dark');
        }
        //  else if (new Date().getHours() >= 22 || new Date().getHours() < 7) {
        // document.body.classList.add('dark');
        // } 
        else if (matchMedia('(prefers-color-scheme: dark)').matches) {
        document.body.classList.add('dark');
        }
    </script>
    <a onclick="switchNightMode()" id="sma">
        <i class="fa fa-moon-o" id="nightMode" aria-hidden="true"></i>
    </a>
    <!-- 网站全局深色模式设置结束 -->

    <!-- 网站主题切换模式开始 -->
    <!-- 中国节日按钮开始 -->
    <script>
        if (localStorage.getItem('themespring') === '1') {
            document.body.classList.add('themespring');
        }
        else if (matchMedia('(prefers-color-scheme: themespring)').matches) {
            document.body.classList.add('themespring');
        }
    </script>
    <div onclick="switchSpringThemes()" id="switchspring">
        <img class="chunjiepic" src="/medias/spring-img/denglong.png" title="春节主题" />
    </div>
    <!-- 中国节日按钮结束  -->
    <!-- 网站主题切换模式结束 -->

    <!-- header模块开始 -->
<header class="navbar-fixed" id="header-active">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.webp" class="logo-img" alt="LOGO">
                    
                    <!-- 大屏幕下logo字体 -->
                    <span class="bigwidth">Oliver-Blog</span>
                    <!-- 小屏幕下logo字体 -->
                    <span class="smallwidth">Oliver</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="javascript:;" class="waves-effect waves-light">

      
      <span>归档</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/tags">
          
          <span>标签</span>
        </a>
      </li>
      
      <li>
        <a href="/archives">
          
          <span>日历</span>
        </a>
      </li>
      
      <li>
        <a href="/count">
          
          <span>统计</span>
        </a>
      </li>
      
      <!-- 波浪wave条 -->
      <div class="wavelineerji">
        <style>
          .wavelineerji {
            background: url(/medias/wave.png) 0 0 repeat-x;
            height: 3px;
            width: 100%;
            position: absolute;
            left: 0;
            bottom: -3px;
            background-size: 10px 3px;
            transform: rotate(180deg);
          }
        </style>
      </div>
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="javascript:;" class="waves-effect waves-light">

      
      <span>清单</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/books">
          
          <span>书单</span>
        </a>
      </li>
      
      <!-- 波浪wave条 -->
      <div class="wavelineerji">
        <style>
          .wavelineerji {
            background: url(/medias/wave.png) 0 0 repeat-x;
            height: 3px;
            width: 100%;
            position: absolute;
            left: 0;
            bottom: -3px;
            background-size: 10px 3px;
            transform: rotate(180deg);
          }
        </style>
      </div>
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="javascript:;" class="waves-effect waves-light">

      
      <span>实验室</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/ticktack">
          
          <span>ticktack</span>
        </a>
      </li>
      
      <!-- 波浪wave条 -->
      <div class="wavelineerji">
        <style>
          .wavelineerji {
            background: url(/medias/wave.png) 0 0 repeat-x;
            height: 3px;
            width: 100%;
            position: absolute;
            left: 0;
            bottom: -3px;
            background-size: 10px 3px;
            transform: rotate(180deg);
          }
        </style>
      </div>
    </ul>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.webp" class="logo-img circle responsive-img">
        
        <div class="logo-name">Oliver博客</div>
        <div class="logo-desc">
            
            这里是网站描述
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
				<i class="fas fa-fw"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
				<i class="fas fa-fw"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fas fa-fw"></i>
			
			归档
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/tags " style="margin-left:75px">
				  
		          <span>标签</span>
                  </a>
                </li>
              
                <li>

                  <a href="/archives " style="margin-left:75px">
				  
		          <span>日历</span>
                  </a>
                </li>
              
                <li>

                  <a href="/count " style="margin-left:75px">
				  
		          <span>统计</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
				<i class="fas fa-fw"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fas fa-fw"></i>
			
			清单
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/books " style="margin-left:75px">
				  
		          <span>书单</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
				<i class="fas fa-fw"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fas fa-fw"></i>
			
			实验室
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/ticktack " style="margin-left:75px">
				  
		          <span>ticktack</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        
    </ul>
</div>


        </div>
        <style>
          .brand-logo .waves-effect {
            font-size: 24px;
            font-style: oblique;
            color: #fadca6;
          }
        </style>
        
        
    </nav>
</header>
<!-- header模块结束 -->

<!-- 春节主题模式样式开始 -->
<style>
    .denglong {
        display: none;
    }
    body.themespring .denglong {
        display: block;
    }
    @media only screen and (min-width: 1124px) {
        .nav-menu {
            padding-right: 0px;
        }
        body.themespring .nav-menu {
            padding-right: 96px;
        }
    }
    @media only screen and (max-width: 760px) {
        .deng-box, .deng-box1 {
            width: 40%;
        }
        body.themespring .right {
            float: left!important;
        }
    }
    @media only screen and (min-width: 768px) and (max-width: 1024px) {
        .right {
            float: left!important;
        }
    }
    .deng-box {
        position: fixed;
        top: -40px;
        right: -20px;
        z-index: 999;
    }
    .deng-box1 {
        position: fixed;
        top: -30px;
        right: 10px;
        z-index: 999;
    }
    .deng-box1 .deng {
        position: relative;
        width: 120px;
        height: 90px;
        margin: 50px;
        background: #d8000f;
        background: rgba(216, 0, 15, 0.8);
        border-radius: 50% 50%;
        -webkit-transform-origin: 50% -100px;
        -webkit-animation: swing 5s infinite ease-in-out;
        box-shadow: -5px 5px 30px 4px rgba(252, 144, 61, 1);
    }
    .deng {
        position: relative;
        width: 120px;
        height: 90px;
        margin: 50px;
        background: #d8000f;
        background: rgba(216, 0, 15, 0.8);
        border-radius: 50% 50%;
        -webkit-transform-origin: 50% -100px;
        -webkit-animation: swing 3s infinite ease-in-out;
        box-shadow: -5px 5px 50px 4px rgba(250, 108, 0, 1);
    }
    .deng-a {
        width: 100px;
        height: 90px;
        background: #d8000f;
        background: rgba(216, 0, 15, 0.1);
        margin: 12px 8px 8px 10px;
        border-radius: 50% 50%;
        border: 2px solid #dc8f03;
    }
    .deng-b {
        width: 45px;
        height: 90px;
        background: #d8000f;
        background: rgba(216, 0, 15, 0.1);
        margin: -4px 8px 8px 26px;
        border-radius: 50% 50%;
        border: 2px solid #dc8f03;
    }
    .xian {
        position: absolute;
        top: -20px;
        left: 60px;
        width: 2px;
        height: 20px;
        background: #dc8f03;
    }
    .shui-a {
        position: relative;
        width: 5px;
        height: 20px;
        margin: -5px 0 0 59px;
        -webkit-animation: swing 4s infinite ease-in-out;
        -webkit-transform-origin: 50% -45px;
        background: #ffa500;
        border-radius: 0 0 5px 5px;
    }
    .shui-b {
        position: absolute;
        top: 14px;
        left: -2px;
        width: 10px;
        height: 10px;
        background: #dc8f03;
        border-radius: 50%;
    }
    .shui-c {
        position: absolute;
        top: 18px;
        left: -2px;
        width: 10px;
        height: 35px;
        background: #ffa500;
        border-radius: 0 0 0 5px;
    }
    .deng:before {
        position: absolute;
        top: -7px;
        left: 29px;
        height: 12px;
        width: 60px;
        content: " ";
        display: block;
        z-index: 999;
        border-radius: 5px 5px 0 0;
        border: solid 1px #dc8f03;
        background: #ffa500;
        background: linear-gradient(to right, #dc8f03, #ffa500, #dc8f03, #ffa500, #dc8f03);
    }
    .deng:after {
        position: absolute;
        bottom: -7px;
        left: 10px;
        height: 12px;
        width: 60px;
        content: " ";
        display: block;
        margin-left: 20px;
        border-radius: 0 0 5px 5px;
        border: solid 1px #dc8f03;
        background: #ffa500;
        background: linear-gradient(to right, #dc8f03, #ffa500, #dc8f03, #ffa500, #dc8f03);
    }
    @font-face {
        font-family: "华文行楷";
        src: url('/fonts/华文行楷.ttf');
    }
    .deng-t {
        font-family: 华文行楷;
        font-size: 26px;
        color: #dc8f03;
        font-weight: bold;
        line-height: 44px;
        text-align: center;
    }
    .night .deng-t,
    .night .deng-box,
    .night .deng-box1 {
        background: transparent !important;
    }
    @-moz-keyframes swing {
        0% {
                -moz-transform: rotate(-10deg)
        }
        50% {
             -moz-transform: rotate(10deg)
        }
        100% {
                -moz-transform: rotate(-10deg)
        }
    }
    @-webkit-keyframes swing {
        0% {
                -webkit-transform: rotate(-10deg)
        }
        50% {
                -webkit-transform: rotate(10deg)
        }
        100% {
                -webkit-transform: rotate(-10deg)
        }
    }
</style>
<div class="denglong">
    <div class="deng-box">
        <div class="deng">
            <div class="xian"></div>
            <div class="deng-a">
                <div class="deng-b"><div class="deng-t" id="dtone">喜迎</div></div>
            </div>
            <div class="shui shui-a"><div class="shui-c"></div><div class="shui-b"></div></div>
        </div>
    </div>
    <div class="deng-box1">
        <div class="deng">
            <div class="xian"></div>
            <div class="deng-a">
                <div class="deng-b"><div class="deng-t" id="dttwo">春节</div></div>
            </div>
            <div class="shui shui-a"><div class="shui-c"></div><div class="shui-b"></div></div>
        </div>
    </div>
</div>
<!-- 春节主题模式样式结束 -->

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/banner/1.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">R language learning Notes</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">
    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
    .suibis[data-spmid="随笔"] {
        width: 100%!important;
    }
    .toc-widget[data-spmid="随笔"],
    #floating-toc-btn[data-spmid="随笔"]
    {
        display: none!important;
    }
     
</style>

<div class="row">
    
    
        <div id="main-content" class="col s12 m12 l9 suibis" data-spmid="R">
            <style>
    #switchspring {
        bottom: 223px!important;
    }
    @media only screen and (max-width: 601px) {
        #switchspring {
            bottom: 178px!important;
        }
    }
    #switchchristmas {
        bottom: 281px!important;
    }
    @media only screen and (max-width: 601px) {
        #switchchristmas {
            bottom: 235px!important;
        }
    }
    .ititle {
        margin: 15px 0;
        text-align:center;
        font-family: 'Architects Daughter', cursive;
    }
    .ipage {
        line-height: 30px;
        margin: 0 auto;
        padding: 15px 32px 29px;
        background-color: #f9f9f9;
        box-shadow: 0px 2px 5px 0px rgba(0, 0, 0, 0.26);
        -moz-border-radius-bottomleft: 20px 500px;
        -moz-border-radius-bottomright: 500px 30px;
        -moz-border-radius-topright: 5px 100px;	
        -webkit-border-bottom-left-radius: 20px 500px;
        -webkit-border-bottom-right-radius: 64px 10px;
        -webkit-border-top-right-radius: 5px 100px;    
        border-bottom-left-radius: 20px 500px;
        border-bottom-right-radius: 64px 10px;
        border-top-right-radius: 5px 100px;           
        -webkit-background-size: 100% 30px;
        -moz-box-shadow: 0 2px 10px 1px rgba(0, 0, 0, 0.2);
        -webkit-box-shadow: 0 2px 10px 1px rgba(0, 0, 0, 0.2);
        text-shadow: 0 1px 0 #F6EF97;
        position: relative;
    }
.izhengwen {
    position: relative;
    top: 0;
    left: 0;
    z-index: 2;
    height: auto;
    background: repeating-linear-gradient(to bottom, #f9f9f9, #f9f9f9 31px, #6BA2D8 1px, #f9f9f9);
    background-size: 100% 32px;
}
.izhengwen p {
    letter-spacing: .1rem;
}
#articleContent p {
    margin: 0
}
.ititle {
    font-family: 'Architects Daughter', cursive;
    font-size: 1.45rem!important;
    padding: 10px auto;
}
.izhengwen p {
    position: relative;
    line-height: 2.2rem!important;
    text-indent: 2em;
    font-family: 'Architects Daughter', cursive!important;
    font-size: 1.45rem!important;
}
.ipage::before {
    content: " ";
    display: inline-block;
    position: absolute;
    top: 0px;
    bottom: 0;
    right: 52px;
    z-index: 4;
    width: 4px;
    height: 100%;
    border-left: 1px solid #fca1a1;
}
.izhengwen p:nth-child(odd):before {
    content: " ";
    display: inline-block;
    position: absolute;
    top: 0;
    left: -16px;
    z-index: 3;
    width: 24px;
    height: 24px;
    background-color: #fff;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;
    box-shadow: inset 0px 2px 5px 0px rgba(0, 0, 0, 0.26);
}
.ipage:after {
    content: " ";
    display: inline-block;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 52px;
    z-index: 3;
    width: 4px;
    height: 100%;
    border-left: 4px double #fca1a1;
}
.ipage p {
    padding: 0 2em;
    color: #333!important;
}
body.dark .ipage {
    opacity: 0.85;
}
/*小屏幕下(手机类)的样式*/
@media only screen and (max-width: 600px) {
    .ipage {
        padding: 15px 23px 29px;
    }
    .ipage:after {
        left: 36px;
    }
    .ipage::before {
        right: 36px;    
    }
    .ipage p, .ititle {
        padding: 0 0.9em;
    }

}
h3 {
    font-size: 1.32rem;
    font-weight: 400;
    color: #101012;
    transition: 0.8s;
    cursor: pointer;
}
h3:hover {
    transform: translateX(15px);
}
</style>

<!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        
        <div class="card-content article-info">
            <!-- 福袋按钮 -->
            <div class="caishendeng">        
                <div class="guguxian wenzhangxian">
                    <img class="caishenpic gugus" src="/medias/spring-img/caishen.png" />
                </div>              
            </div>
            <!-- 圣诞按钮 -->
            <div class="shengdandeng">        
                <div class="shengdanxian" style="left: 50%;">
                    <img class="shengdanpic fudai" src="/medias/christmas-img/shengdanren4.png" />
                </div>              
            </div>
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/R/">
                                <span class="chip bg-color">R</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E7%94%B5%E8%84%91%E8%BD%AF%E4%BB%B6/" class="post-category">
                                电脑软件
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2023-05-30
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    866
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    3 分
                </div>
                

                
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>《R语言数据分析从入门到进阶》是我在哔哩哔哩看的R语言教程，个人觉得很不错，所以把学习笔记分享出来，笔记来源：<a target="_blank" rel="noopener" href="https://space.bilibili.com/253810656">模型机器数据科学</a></p>
<h2 id="1-入门知识"><a href="#1-入门知识" class="headerlink" title="1.入门知识"></a>1.入门知识</h2><blockquote>
<p>入门知识部分，主要介绍R语言相关软件安装与设置，相关资料网站，包的安装、加载、更新、移除等管理操作，帮助获取，工作目录的查看与设置，代码相关文件，内置数据加载等内容。</p>
</blockquote>
<pre class=" language-lang-R"><code class="language-lang-R"># R、RStudio安装
# https://mirrors.ustc.edu.cn/CRAN/
# https://rstudio.com/products/rstudio/download/
# 网站说明task，packages list，package page
# 界面布局、显示、中文编码问题说明

######################################################

# 包

# 包的安装
# 运行:Ctrl+Enter
install.packages("car")
# 建议在线安装，不建议本地安装(即不要去官网下载压缩包)
# 包的加载
library(car)
#library(caret) 机器学习的包
# 单独加载包内的某个函数
# car::vif()
# vif()是car中的某个函数
# 更新包
update.packages() # 更新所有包，逐个提示
# 更新指定包，以包名称作为参数即可
# 移除包
remove.packages("car")

# library(tidyverse)
# 如果包里的名字重复，后者加载入的包会覆盖前面加载进来的，这时就需要使用类似car::vif()这样的操作
######################################################

# 获取帮助
# 某个函数的帮助
?help
help("library")
# 某个关键词的帮助，下面是搜索包含help的帮助
??help
# 某个关键词的帮助，下面是搜索包含library的帮助
help.search("library")
# 某个package的帮助
help(package = "ggplot2")

# 获取当前工作目录
getwd()
# 设置工作目录
setwd("D:/R")
# 获取文件路径
file.choose()
# read.csv(file.choose())
#括号里的是文件的路径，根据file.choose()获取，上述操作推荐使用，简约化
# 转义字符 \
# rstudio的项目(工程)创建
# .Rhistory文件表示的是之前运行过的文件
# 保存R文件.RData
# 以后打开记得用.RData
# 直接鼠标点击
save()
save.image()
# 加载RData文件，如果需要之前运行的数据，就去运行下面这段代码
load(file.choose())

# 加载某个包内置的数据集
data()

# 列示当前环境中的对象
ls()
# 移除某个对象
rm()
# 移除所有对象
rm(list = ls())
</code></pre>
<p>记录于——2023.6.3</p>
<h2 id="2-数据基本知识"><a href="#2-数据基本知识" class="headerlink" title="2.数据基本知识"></a>2.数据基本知识</h2><blockquote>
<p>数据基本知识部分，主要介绍数值型、字符型、逻辑型三种数据类型以及对应的判断和转换函数，向量、矩阵、列表、数据框等数据结构以及对应的构建函数、属性函数和索引方法，对R语言中的特殊值、常量也有相应的介绍。</p>
</blockquote>
<pre class=" language-lang-R"><code class="language-lang-R">######################################################

# R常用数据类型
# 数值型
123
2.34

# 字符型
"Hello, World."
'123'

# 逻辑型，都大写
TRUE
T
FALSE
F

# 判断，is函数
# 是否为数值型
is.numeric(123)
is.numeric(FALSE)
# 是否为字符型
is.character('123')
is.character(FALSE)
# 是否为逻辑型
is.logical('123')
is.logical(FALSE)

# 转换，as函数
# 转换为数值型
as.numeric('123')
as.numeric('转换')
as.numeric(T)
as.numeric(F)
# 转换为字符型
as.character(123)
# 转换为逻辑型
as.logical("Hello, World.")
as.logical(2)
as.logical(1)
as.logical(-2)
as.logical(2.1)
as.logical(0)


# 特殊值 部分大写，按照下面的书写格式
# 缺失值
NA
is.na(NA)
# 空值
NULL
is.null(NULL)
# 不是一个数值
NaN
is.nan(NaN)
# 正无穷
Inf
# 负无穷
-Inf
is.infinite(-Inf)

# 示例
2/0
-2/0
# NaN
0/0

######################################################
######################################################

# R常用数据结构

# 赋值
# 对象名 <- 对象值
# =
# 快捷键 alt + -

# 向量

# 常量
pi
# 小写字母
letters
# 大写字母
LETTERS
# 月份的全称
month.name
# 月份的简称
month.abb

v1 <- 1:5
# 连接函数c
v2 <- c(3,2,7,4,6)
v2 <- c(v1,3,2,7,4,6)
# repeat,sequence
# times:整体重复
# each:每个元素重复
v3 <- rep(v2, times = 2)
# 结果1 2 3 4 5 3 2 7 4 6 1 2 3 4 5 3 2 7 4 6
v4 <- rep(v2, each = 2)
# 结果1 1 2 2 3 3 4 4 5 5 3 3 2 2 7 7 4 4 6 6
# 先each，后times
v5 <- rep(v2, times = 2, each = 2)
# 结果1 1 2 2 3 3 4 4 5 5 3 3 2 2 7 7 4 4 6 6 1 1 2 2 3 3 4 4 5 5 3 3 2 2 7 7 4 4 6 6
# by为步长
v6 <- seq(from = 2, to = 9, by = 3)
# 结果2 5 8
# length.out元素的个数
v7 <- seq(from = 2, to = 9, length.out = 3)
# 结果2.0 5.5 9.0
v8 <- seq(from = 2, by = 3, length.out = 4)
# 结果2 5 8 11
v9 <- c('aic', 'bic', 'cp')
rep(v9, each = 3)

c(T,T, F,T)

# 强制转换为同一种类型的数据
# 存在字符就全部转化成字符，不存在字符存在数值就转换成数值
c(T, "aic")

# 向量元素名称
names(v2)
names(v2) <- v9
v2
# 输出
# aic  bic   cp <NA> <NA> <NA> <NA> <NA> <NA> <NA> 
#  1    2    3    4    5    3    2    7    4    6 
# 向量长度
length(v9)
length(v9) <- 9
# v9结果
# "aic" "bic" "cp"  NA    NA    NA    NA    NA    NA
# 向量索引，索引从1开始，python是从0开始
v8[3]
# 连接1，3，5的位置的元素
v8[c(1, 3, 5)]
# 排除掉第一个位置和第四个位置
v8[-c(1, 4)]
v2[c('aic', 'cp')]
# aic  cp 
#  1   3 
# %%:余数，模
v1[v1%%2==1]

######################################################

# 矩阵，矩阵只接受一种数据类型&向量
m1 <- matrix(
  1:6,
  nrow = 2,
  # ncol = 3,
  byrow = F,
  dimnames = list(c('r1', 'r2'),
                  c('c1', 'c2', 'c3'))
)
m1

# matrix(NA, ncol = 3, nrow = 3)

m2 <- matrix(
  c(1:6,letters[1:6]),
  nrow = 3,
  byrow = F,
  dimnames = list(c('r1', 'r2', 'r3'),
                  c('c1', 'c2', 'c3', 'c4'))
)
m2

# 行列名称
colnames(m1)
rownames(m1)
dimnames(m2)

# 维度信息
dim(m1)
ncol(m1)
nrow(m1)

# 矩阵索引 逗号前面是行，逗号后面是列
m2[1,2] # 返回向量
m2[1,] # 返回向量
m2[,2] # 返回向量
m2[1:2,2:3] # 返回矩阵
# 一三行，二四列
m2[c(1,3), c(2,4)]

m1['r1',] # 返回向量
m1[,'c1'] # 返回向量
m1[c('r1','r2'), c('c2','c3')] # 返回矩阵

# 转换成向量，按列抽取
as.vector()

# 数组
# array()
######################################################

# 列表
v1 <- 1:5
m1 <- matrix(
  1:6,
  nrow = 2,
  # ncol = 3,
  byrow = F,
  dimnames = list(c('r1', 'r2'),
                  c('c1', 'c2', 'c3'))
)
l1 <- list(com1 = v1,
           com2 = m1)
l1

# 长度信息
length(l1)

# 名称
names(l1)

# 列表索引
l1$com1 # 返回向量
l1[['com2']] # 返回矩阵
l1[[2]] # 返回矩阵

l1['com1'] # 返回列表
l1[2] # 返回列表

# 新建成分
l1$com3 <- 3:6
l1

# 释放列表
unlist()

######################################################

# 数据框（特殊的列表）,矩阵元素只能是一种数据类型
df1 <- data.frame(
  c1 = 2:5,
  c2 = LETTERS[2:5]
)
df1

# 维度信息
dim(df1)
ncol(df1)
nrow(df1)

# 行列名称
names(df1)
colnames(df1)
rownames(df1)

# 数据框索引，如果返回列就是向量，行就是数据框
df1[1:2, 2] # 返回向量
df1[, 2] # 返回向量
df1[1, ] # 返回数据框

df1[, "c1"] # 返回向量
df1['1',] # 返回数据框

df1[[2]] # 返回向量
df1$c1 # 返回向量

df1[2] # 返回数据框
df1['c1'] # 返回数据框

# 新建列
df1$c3 <- 1:4
# 可以修改列,同样矩阵也可以这样修改
df1$c2 <- 1:4
df1

# 生成用于网格搜索的数据框
expand.grid(mtry = 2:5,
            ntree = c(200, 500))
# 先选mtry个自变量，再从中选择最优的变量，ntree多少棵决策树
######################################################
</code></pre>
<p>记录于——2023.6.4</p>
<h2 id="3-基本运算和常用函数"><a href="#3-基本运算和常用函数" class="headerlink" title="3.基本运算和常用函数"></a>3.基本运算和常用函数</h2><blockquote>
<p>基本运算和常用函数部分，主要介绍常用的数学计算函数，逻辑运算函数，字符处理函数，随机分布函数，向量、数据框、矩阵相关的函数。</p>
</blockquote>
<pre class=" language-lang-R"><code class="language-lang-R"># 常见运算与函数

############################################ 基本运算

1 + 2                          # 加
3 - 2                          # 减
3 * 4                          # 乘
8 / 5                          # 除

c(1:4) / c(2:5)     #相同位置相除
c(1:6) / c(2:5)  # 循环扩展

4 ^ 3                          # 幂运算 底数^指数
exp(1) # 自然常数为底的幂运算
log(x = 25, base = 5) # 5为底25的对数
sqrt(4) # 开平方
abs(-5.6) # 绝对值
sign(-5.6) # 符号函数
round(3.45679, 2) # 保留指定位小数
signif(3.245, 2) # 保留指定位有效数字
ceiling(3.2) # 天花板
# 4
floor(3.2) # 地板
# 3

2 == 3
2 != 3
2 > 3
2 >= 3
2 < 3
2 <= 3
# 2是否包含于2~5的向量
# 二元操作符
2 %in% 2:5

(2 > 3) & (2 %in% 2:5) # 与
(2 > 3) | (2 %in% 2:5) # 或
!(2 %in% 2:5) # 非

############################################ 向量相关函数

v2 <- c(3,2,7,4,6,8,11,21)
max(v2) # 最大值
cummax(v2) # 累积最大值

min(v2) # 最小值
cummin(v2) # 累积最小值

sum(v2) # 求和
cumsum(v2) # 累积求和

prod(v2) # 乘积
cumprod(v2) # 累积乘积

mean(v2) # 均值
median(v2) # 中位数
sd(v2) # 标准差
var(v2) # 方差

rev(v2) # 向量逆转
sort(v2) # 向量重排

v5 <- rep(v2, times = 2)
table(v5) # 向量元素频数统计
unique(v5) # 向量的取值水平，去除重复的，只保留一个

# 索引函数
which(v5==7)
# 显示第一次出先最大/最小的位置，索引从1开始
which.max(v5)
which.min(v5)

# 交集
intersect(1:5, 4:7)
# 差集，前面有，后面没有，前面减去后面的元素
setdiff(1:5, 4:7)
# 并集，去除重复的，唯一值
union(1:5, 4:7)

############################################ 数据框和矩阵相关函数

dfs <- data.frame(
  a=1:5,
  b=3:7,
  d=letters[1:5]
)

# 行列合并，行合并就是行变多了，列合并就是列变多了，bingrows和bindcolumns可以操作的对象维度更高
df1 <- dfs[1:3, ]
df1
df2 <- dfs[3:5, ]
df2
# 行合并
rbind(df1, df2) # 要求列数、列名称相同
# 列合并
cbind(df1, df2) # 要求行数相同

# 行列运算
# 按列运算
colMeans(dfs[,1:2])
colSums(dfs[,1:2])
# 按行运算
rowMeans(dfs[,1:2])
rowSums(dfs[,1:2])

# margin 1对应行，2对应列，sd是标准差
# apply(x, margin, function)
apply(dfs[,1:2], 2, sd)
apply(
  dfs[,1:2],
  2,
  function(x)&#123;sum(is.na(x))&#125;
)


# 对象结构信息
str(dfs)
# 对象的信息
summary(dfs)
View(dfs)
# 默认是6行，可以指定n，n为行数
head(dfs, n = 2)
tail(dfs, n = 2)


# 矩阵运算
m3 <- matrix(
  c(5,7,3,4),
  ncol=2,
  byrow=T
)
m3

m4 <- matrix(
  c(5,7,3,4,8,9),
  ncol=3,
  byrow=T
)
m4
# 转置
t(m3)
# 行列式
det(m3)
# 矩阵的乘法
m3 %*% m4
solve(m3) # m3 %*% x = E
solve(m3, m4) # m3 %*% x = m4

############################################ 字符函数与分布相关函数

# 连接成字符向量
paste(1:5, collapse = "+")
# "1+2+3+4+5"
paste(letters[1:5], collapse = "-")
paste(1:5, letters[1:8], sep = "~")
# "1~a" "2~b" "3~c" "4~d" "5~e" "1~f" "2~g" "3~h"
paste0(1:5, letters[1:8])
# "1a" "2b" "3c" "4d" "5e" "1f" "2g" "3h"
# 字符长度
nchar(month.name)
# 7 8 5 5 3 4 4 6 9 7 8 8
# 全部转大写
toupper(month.name)
# 全部转小写
tolower(month.name)
# 含有某个字符的元素的索引
grep("Ju", month.name)
# 6 7
# 替换字符，将e替换为000
gsub("e", "000", month.name)
# [1] "January"         "F000bruary"     
# [3] "March"           "April"          
# [5] "May"             "Jun000"         
# [7] "July"            "August"         
# [9] "S000pt000mb000r" "Octob000r"      
# [11] "Nov000mb000r"    "D000c000mb000r" 
# 随机分布函数
# 保证结果不变
set.seed(24)
# 1和2的元素，抽12个样本，有放回的则为T
# r-生成随机数，p-累积概率，q-分位数，d-概率密度，norm-分布
# mean均值，sd标准差，pnorm和qnorm互为反函数
sample(1:2, 12, replace = T) # 随机抽样
rnorm(10, mean = 1, sd = 2)
pnorm(1, mean = 1, sd = 2)
qnorm(0.5, mean = 1, sd = 2)
dnorm(1, mean = 1, sd = 2)

plot(x = seq(-5, 7, length=1000),
     y = dnorm(seq(-5, 7, length=1000),
               mean = 1,
               sd = 2),
     type = "l",#线
     ylim = c(0, 0.25))
abline(h = 0,
       v = 1)
# x=1直线
</code></pre>
<p>记录于——2023.6.5</p>
<h2 id="4-语法代码"><a href="#4-语法代码" class="headerlink" title="4.语法代码"></a>4.语法代码</h2><blockquote>
<p>语法部分，主要介绍R语言中循环语句、条件语句的构建，如何自定义函数。</p>
</blockquote>
<pre class=" language-lang-R"><code class="language-lang-R"># 循环结构 向量化编程、泛函式编程
# for循环,循环变量一般为向量
for (x in c(-2, 3, 0, 4)) &#123;
  print(x)
  y = abs(x)
  z = y^3
  print(z)
  print("-------")
&#125;



# while循环
v1 <- 1:5
i <- 1
while (i <= length(v1)) &#123;
  print(i)

  print(sum(v1[1:i]))
  i = i + 1

  print(i)
  print("####")
&#125;


# 示例
df <- data.frame(c1 = 2:5,
                 c2 = 4:7,
                 c3 = -19:-16)

for (i in 1:nrow(df)) &#123;
  print(sum(df[i, ]))
&#125;


j = 1
while(j <= nrow(df)) &#123;
  print(sum(df[j, ]))
  j = j + 1
&#125;

# next
# break

######################################################

# 条件结构
a <- 7
if(a > 6) &#123;
  print("a>6")
&#125;

a <- 5
if(a > 6) &#123;
  print("a>6")
&#125; else &#123;
  print('a<=6')
&#125;

a <- 2
if(a > 6) &#123;
  print("a>6")
&#125; else if (a>3)&#123;
  print('a>3')
&#125; else &#123;
  print('a<=3')
&#125;


s = 40
# %%取余
if(s %% 2 == 0) &#123;
  print("s是偶数。")
&#125; else &#123;
  print("s是奇数。")
&#125;


ifelse(55 %% 2 == 0, "偶数", "奇数")

######################################################


# 函数构建
# 求阶层
f1 <- function(aug1)&#123;
  res1 <- 1:aug1
  # prod求乘积
  res2 <- prod(res1)
  return(res2)
&#125;
f1(aug1 = 10)
f1(10)


f2 <- function(aug1, aug2=4)&#123;
  res <- aug1 + aug2
  return(res)
&#125;

f2(34)
f2(34, 5)


######################################################
</code></pre>
<p>记录于——2023.6.6</p>
<h2 id="5-数据整理"><a href="#5-数据整理" class="headerlink" title="5.数据整理"></a>5.数据整理</h2><blockquote>
<p>数据整理部分，主要介绍数据文件的导入导出、批量导入，依托tidyverse包进行行过滤、列筛选、分组统计汇总、数据框合并、列的分解与合并、长宽数据转换等。</p>
</blockquote>
<pre class=" language-lang-R"><code class="language-lang-R">######################################################

# 数据操作——暨tidyverse包函数精讲
library(tidyverse)
# 组成包介绍
# https://www.tidyverse.org/
# ggplot2作图
# forcats处理因子型数据
# tibble类似于dataframe的一种结构
# readr读取外源数据
# dplyr数据整理
# stringr字符处理

######################################################

# csv数据导入，csv是逗号分隔符文件
rawdata <- read.table(file.choose(), header = T, sep = ",")
head(rawdata, n=4)
tail(rawdata, n=10)
rawdata[95:105,]
# rawdata的结构显示
str(rawdata)
# read.csv(file.choose())，推荐csv，是针对csv文件设计的
# 可以大文件使用，大数据集
# data.table::fread(file.choose())

# csv数据导出，csv是逗号分隔符文件
write.table(rawdata,
            "test.csv",
            sep = ",",
            row.names = F)
# write.csv()
# data.table::fwrite()

# 读取excel表，需指定sheet，默认读取第一张表
# csv只有一张表，但是excel可以有多张表
# readx1属于tidyverse的子包
library(readxl)
# 返回excel里有多少张表，记得路径要为英文
# excel_sheets(file.choose())
data1 <- read_excel(file.choose())


# 批量读取数据，读取当前文件夹下房地产PB的所有的文件的sheet1
# .表示访问当前
files <- list.files(".\\房地产PB\\")
files
paths <- paste(".\\房地产PB\\", files, sep = "")
paths

df <- list()
for (i in 1:length(paths)) &#123;
  datai <- read_excel(paths[i])
    # str_sub取字符的子集
  datai$object <- str_sub(files[i], start = 1, end = -6)
  df[[i]] <- datai
  print(i)
&#125;
# bind_rows将若干个dataframe按行进行拼接，如果不拼接就是dataframe
df_all <- bind_rows(df)


######################################################


# dplyr
library(dplyr)
# ToothGrowth是自带的数据
head(ToothGrowth)
str(ToothGrowth)

# 新增变量和变量重新赋值
# nv > median(nv), "H", "L" 如果真，则H，否则L
toothgrowth2 <- mutate(ToothGrowth,
                       len = len^2,
                       nv = 1:nrow(ToothGrowth),
                       nv2 = ifelse(nv > median(nv), "H", "L"))
head(toothgrowth2)


# 筛选行（样本）
# %in%是否包含于
toothgrowth3 <- filter(toothgrowth2,
                       nv %in% 1:50,
                       nv2 == "H")
toothgrowth3

# 筛选列（变量）
toothgrowth4 <- select(toothgrowth3,
                       c(2,4))
head(toothgrowth4)

# 分组计算
summarise(ToothGrowth, len_max = max(len), len_min = min(len))
summarise(group_by(ToothGrowth, supp), len_max = max(len))
summarise(group_by(ToothGrowth, dose), len_max = max(len))
summarise(group_by(ToothGrowth, dose, supp), len_max = max(len))


# 管道操作符
# 一连串的操作一连串的代码，ToothGrowth为左边的参数
library(magrittr)
ToothGrowth %>%
  mutate(nv = 1:nrow(ToothGrowth)) %>%
  filter(nv %in% 1:50) %>%
  select(1:2) %>%
  group_by(supp) %>%
  summarise(len_max = max(len)) %>%
  as.data.frame()


# 连接（合并）数据框
library(dplyr)
df1 <- data.frame(c1 = 2:5,
                  c2 = LETTERS[2:5])
df1
df2 <- data.frame(c3 = LETTERS[c(2:3,20:23)],
                  c4 = sample(1:100, size = 6))
df2

# 左连接
# 保留c的第一列c2和左连接的部分的数据列
left_join(df1, df2, by = c('c2' = 'c3'))
df1 %>% left_join(df2, by = c('c2' = 'c3'))

# 右连接
df1 %>% right_join(df2, by = c('c2' = 'c3'))

# 全连接，并集，匹配不上的为na
df1 %>% full_join(df2, by = c('c2' = 'c3'))

# 内连接，交集，匹配不上的不显示
df1 %>% inner_join(df2, by = c('c2' = 'c3'))



######################################################

# 列的分裂与合并
library(tidyr)
# 分裂
df3 <- data.frame(c5 = paste(letters[1:3], 1:3, sep = "-"),
                  c6 = paste(letters[1:3], 1:3, sep = "."),
                  c4 = c("B", "B", "B"),
                  c3 = c("H", "M", "L"))
df3
df4 <- df3 %>%
  separate(col = c5, sep = "-", into = c("c7", "c8"), remove = F) %>%
  separate(col = c6, sep = "\\.", into = c("c9", "c10"), remove = T)
df4


# 合并
df4 %>%
  unite(col = "c11", c("c7", "c8"), sep = "_", remove = F) %>%
  unite(col = "c12", c("c9", "c10"), sep = ".", remove = T) %>%
  unite(col = "c13", c("c4", "c3"), sep = "", remove = F)

#########

# 长宽数据转换
library(tidyr)
# 宽数据转长数据
set.seed(42)
df5 <- data.frame(time = rep(2011:2013, each=3),
                  area = rep(letters[1:3], times=3),
                  pop = sample(100:1000, 9),
                  # 9个随机数，保留两位小数
                  den = round(rnorm(9, mean = 3, sd = 0.1), 2),
                  # 8-12的整数抽取9个，有放回
                  mj = sample(8:12, 9, replace = T))
df5

df6 <- df5 %>%
# 相当于3到5列，排除第一列第二列
# 画图前变为长数据，便于显示
  pivot_longer(cols = -c(1:2),
               names_to = "varb",
               values_to = "value")
df6

# 长数据转宽数据
df6 %>%
  pivot_wider(names_from = c(area, varb),
              values_from = value)

######################################################
</code></pre>
<p>记录于——2023.6.9</p>
<h2 id="6-描述性统计和假设检验"><a href="#6-描述性统计和假设检验" class="headerlink" title="6.描述性统计和假设检验"></a>6.描述性统计和假设检验</h2><blockquote>
<p>描述性统计和假设检验，首先介绍因子，然后介绍如何计算常用描述性统计量、偏度、峰度、相关系数及列联表，假设检验部分依次介绍了正态性分布检验、方差齐性检验、t检验、方差分析以及常用非参数检验。</p>
</blockquote>
<pre class=" language-lang-R"><code class="language-lang-R">######################################################

# 因子
set.seed(42)
l3 <-sample(letters[1:3], 10, replace = T)
l3
as.factor(l3)
factor(l3)
# factor()


# 描述性统计
set.seed(432)
d3 <- data.frame(
  ind = 1:1000,
  rn = rnorm(1000),
  rn2 = rnorm(1000, mean = 2, sd = 3),
  rt = rt(1000, df=5),
  rs1 = as.factor(sample(letters[1:3], 1000, replace = T)),
  rs2 = as.factor(sample(LETTERS[21:22], 1000, replace = T))
)

# 描述性统计结果
summary(d3)
library(skimr)
skim(d3)

# 偏度
e1071::skewness(d3$rn)
# 峰度
e1071::kurtosis(d3$rn2)

# 相关系数
cor(d3$rn, d3$rt)
cor(d3[,2:4])
# 相关性检验
cor.test(d3$rn, d3$rt)
library(psych)
corr.test(d3[,1:3])

# 列联表
table(d3$rs1)
prop.table(table(d3$rs1))


######################################################
# 假设检验

# 正态分布检验
# shapiro.test()
library(rstatix)
head(ToothGrowth)
# 单一变量检验
ToothGrowth %>%
  shapiro_test(len)
# 分组检验
ToothGrowth %>%
  group_by(dose) %>%
  shapiro_test(len)

###########################

# 方差齐性检验
# 两组检验
var.test(len ~ supp, data = ToothGrowth)
# 两组及以上的检验
bartlett.test(len ~ dose, data = ToothGrowth)

##########################

# 均值检验
# t检验
t.test(ToothGrowth$len,
       mu = 18)

t.test(len ~ supp,
       data = ToothGrowth,
       var.equal = T)

# 方差分析
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
aovfit <- aov(len ~ dose, data = ToothGrowth)
aovfit
summary(aovfit)

##########################

# 非参数检验
# 差异检验：Wilcoxon秩和检验(Mann-Whitney U检验)，适用于两组数据
wilcox.test(len ~ supp, data = ToothGrowth, exact = F)
# 差异检验：Kruskal-Wallis检验，适用于两组及以上的数据
kruskal.test(len ~ dose, data = ToothGrowth)

# 方差齐性非参数检验
fligner.test(len ~ dose, data = ToothGrowth)

######################################################
</code></pre>
<blockquote>
<p>线性回归模型介绍了使用R语言构建线性回归模型全流程的内容，从认识数据讲起，到将变量处理为正确的类型，再到构建线性回归模型，提取模型结果，将模型结果格式化输出，对模型进行异方差、自相关、共线性等的检验和修正，最后使用模型进行预测并对预测结果进行可视化和误差评估。</p>
</blockquote>
<pre class=" language-lang-R"><code class="language-lang-R">######################################################


# 普通线性回归
head(mtcars, n = 10)
colnames(mtcars)
rownames(mtcars)
str(mtcars)

# 了解变量，并且把变量处理好
mtcars$vs <- factor(mtcars$vs)
mtcars$am <- factor(mtcars$am)

# 建模
lmfit <- lm(mpg ~ hp + wt + vs + am, data = mtcars)
lmfit
# 模型结果汇总
lmsum <- summary(lmfit)
lmsum
# 模型系数
coef(lmfit)
coef(lmsum)
# 模型残差
resid(lmfit)
# 提取结果成分
str(lmsum)


# 格式化输出
library(stargazer)
# 在console显示表格，输出到本地
stargazer(lmfit, type="text", out="lm.htm")

# 模型诊断
par(mfrow=c(2,2))
plot(lmfit)
library(lmtest)
# 异方差检验
bptest(lmfit)
# 序列相关检验，主要针对时序回归
dwtest(lmfit)
# 修正
library(sandwich)
coeftest(lmfit, vcovHC(lmfit))
coeftest(lmfit, vcovHAC(lmfit))
# 多重共线性检验
library(car)
vif(lmfit)

# 预测
pred <- predict(lmfit, newdata = mtcars)
# 图示
plot(mtcars$mpg, pred)
abline(a=0, b=1, col="red")

# 性能评估
library(caret)
defaultSummary(
  data.frame(obs = mtcars$mpg,
             pred = pred)
)

######################################################
</code></pre>
<blockquote>
<p>logistic回归模型，主要介绍使用R语言构建logistic回归模型用于分类问题的相关内容，内容包括数据读取与整理，模型构建，格式化输出，使用模型进行预测，使用ROC、AUC、混淆矩阵评估模型预测性能等。</p>
</blockquote>
<pre class=" language-lang-R"><code class="language-lang-R">######################################################

# logistic回归
# 读取数据
bcdata <- read.csv(file.choose())

# 查看数据概况
library(skimr)
skim(bcdata)

# 删除含有缺失值的样本
bcdata <- na.omit(bcdata)

# 变量类型修正
bcdata$class <- factor(bcdata$class)

# 查看分类型变量编码
contrasts(bcdata$class)
# 查看分类型变量频数分布
table(bcdata$class)

# logistic回归建模
glmfit <- glm(class ~ .-ID, data = bcdata, family = binomial())
glmfit
summary(glmfit)

# 格式化输出
library(stargazer)
# 在console显示表格，输出到本地
stargazer(glmfit, type="text", out="logit.htm")

# 预测概率
predprob <- predict(glmfit, newdata = bcdata, type = "response")
# 有些模型的predict输出的概率是矩阵，注意识别。

# ROC曲线
library(pROC)
rocs <- roc(response = bcdata$class, # 实际类别
            predictor = predprob) # 预测概率
# 注意Setting direction

# ROC曲线
plot(
  rocs, # roc对象
  print.auc = TRUE, # 打印AUC值
  auc.polygon = TRUE, # 显示AUC区域
  grid = T, # 网格线
  max.auc.polygon = T, # 显示AUC=1的区域
  auc.polygon.col = "skyblue", # AUC区域填充色
  print.thres = T, # 打印最佳临界点
  legacy.axes = T # 横轴显示为1-specificity
)

# 约登法则
bestp <- rocs$thresholds[
  which.max(rocs$sensitivities + rocs$specificities - 1)
]
bestp

# 预测分类
predlab <- as.factor(
  ifelse(predprob > bestp, "malignant", "benign")
)

# 混淆矩阵
library(caret)
confusionMatrix(data = predlab, # 预测类别
                reference = bcdata$class, # 实际类别
                positive = "malignant",
                mode = "everything")
</code></pre>
<h2 id="7-可视化基础-基础绘图函数"><a href="#7-可视化基础-基础绘图函数" class="headerlink" title="7.可视化基础-基础绘图函数"></a>7.可视化基础-基础绘图函数</h2><blockquote>
<p>基础绘图函数部分主要介绍全局设置函数par()函数的常用设置，保存图片，plot函数和低级绘图函数，条形图、箱线图、直方图、密度曲线、马赛克图的绘制等。这部分用到的函数都是R语言自带的函数，属于R语言数据可视化内容的基础部分。</p>
</blockquote>
<pre class=" language-lang-R"><code class="language-lang-R">######################################################

# R语言绘图

# par函数
# 保存初始设定
inipar <- par(no.readonly = T)
# 恢复初始设定
par(inipar)

par(mfrow = c(2,3)) # mfcol
plot(1:30)
plot(1:30)
plot(1:30)

# 保存图片
png("pic.png")
# 绘图过程
plot(1:30)
# 关闭当前绘图设备
dev.off()


#########

# plot函数
plot(x = -1:6,
     y = 2*(-1:6),
     type = "o",
     family = "serif",
     xlim = c(-5,7),
     ylim = c(-5,14),
     ylab = "y----",
     xlab = "----x",
     main = "plot示例")

# lines函数
lines(x = 1:6, y = 2:7, col = "blue")
# abline函数
abline(a = 3, b = 2, col = "green")
abline(v = 0, h = 3)
# text函数
text(x = 3, y = 2.5, labels = "y=3")

#########
set.seed(432)
d0 <- data.frame(rs1 = sample(letters[1:4], 100, replace = T),
                 rs2 = sample(LETTERS[21:22], 100, replace = T))

# barplot函数
barplot(1:5, names.arg = letters[1:5])
barplot(table(d0$rs1), main = "barplot")

# boxplot函数
boxplot(ToothGrowth$len)
boxplot(len ~ supp, data = ToothGrowth)


# hist函数
hist(rnorm(1000), breaks = 15)

# 直方图叠加密度曲线
set.seed(10)
d1 <- rnorm(1000)
hist(d1, breaks = 100, freq = F, main = "Histogram")
lines(density(d1), col = "blue", lwd=2)
d2 <- seq(min(d1), max(d1), length=10000)
lines(d2, dnorm(d2), col = "red", lwd=2)

# 马赛克图
table(d0$rs1)
table(d0$rs2)
table(d0$rs1, d0$rs2)
mosaicplot(table(d0$rs1, d0$rs2))

######################################################
</code></pre>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Oliver博客</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="hhttps://xiaofengboi.gitee.io/posts/671b.html">hhttps://xiaofengboi.gitee.io/posts/671b.html</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Oliver博客</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/R/">
                                    <span class="chip bg-color">R</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="qq,wechat,weibo,douban" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">感谢赞赏哦~</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }
    .v[data-class=v] .emoji, .v[data-class=v] .vemoji {
        max-height: 20px;
        overflow: hidden;
        max-width: 20px!important;
    }
    .v[data-class=v] .vwrap .vemojis {
        text-align: center;
    }
    .roboterbb {
        position: absolute;
        right: 87px;
        padding-top: 3px;
    }
    .robot-check-text:hover {
        color: #26a69a;
    }
    .roboter:hover .robot-check-text::before {
        border: 2px solid #5a5a5a;
    }
    .robotxian {
        background: #5a5a5a;
        top: 21px;
        left: 11px!important;
        transform-origin: 50% -17px;
        animation: swing 3.5s infinite ease-in-out;
        -webkit-transform-origin: 50% -17px;
        -webkit-animation: swing 2.85s infinite ease-in-out;
    }
    .v[data-class=v] .vwrap {
        padding-bottom: 23px;
    }
    .robotimg {
        width: 28px!important;
        height: 28px!important;
        top: 14px!important;
        left: -13px!important;
        max-width: none!important;
        z-index: 99;
        cursor: none!important;
    }
    .v[data-class=v] .vbtn:disabled {
        color: #b2b2b5;
        border-color: #b2b2b5;
    }
    .v[data-class=v] .vbtn:disabled {
        background-color: transparent;
    }
    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }
    .v[data-class=v] .vwrap {
        border-radius: 8px;
    }
    /* #vcomments textarea {
        box-sizing: border-box;
        background: url("/medias/comment_bg1.webp") 100% 100% no-repeat;
    } */
    #vcomments textarea {
        background: url(/medias/comment_bg1.webp) no-repeat;
        background-size: contain;
        background-repeat: no-repeat;
        background-position: right;
        background-color: rgba(255,255,255,0);
        resize: vertical;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #4cbf30;
        font-weight: 500;
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
</style>

<div class="card valine-card" id="vcomments-top">

    <!-- 福袋按钮 -->
    <div class="caishendeng">        
        <div class="caishenxian fudaixian">
            <img class="caishenpic fudao" src="/medias/spring-img/fudao.png" />
        </div>              
    </div>
   
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评 论</span>
    </div>
    <div id="vcomments" class="card-content" style="display: grid"></div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<script>
    new Valine({
        el: '#vcomments',
        enableQQ: true,
        boolean: true,
        appId: 'pVNANpXBOOGmpwtRcRZ93xH0-gzGzoHsz',
        appKey: 'mEALL2rYCYooc8FoGAHa77o8',
        notify: 'false' === 'true',
        verify: 'false' === 'true',
        visitor: 'true' === 'true',
        // avatar: 'mm',
        avatar: '/medias/robot.png',
        pageSize: '16',
        lang: 'zh-cn',
        placeholder: '评论前记得点击下方机器人验证按钮~ （客官留下QQ邮箱可好，会得到及时回复哦~）',    

        adminEmailMd5: '',

        master: [""],
        friends: [""],
        tagMeta: ["博主", "小伙伴", "访客"],
        // tagMeta: '博主,小伙伴,访客',
        // master: '',
        // friends: '',
        emoticonUrl: ["https://cdn.jsdelivr.net/npm/alus@latest"]
    });
</script>
<!-- 直达评论 -->
<div id="to_comment" class="comment-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#vcomments" title="直达评论">
        <i class="fas fa-comments"></i>
    </a>
</div>


<!-- 评论机器人验证 -->
<script>
    $('.roboter').on('click',function(){
        $('.robot-check-text').html('·&nbsp;&nbsp;&nbsp;验证成功！');
        $('.roboter:hover .robot-check-text::before').css('border','2px solid #26a69a');
        $('.robotxian').css('background','#26a69a');
        $('.robotimg').attr('src','/medias/robot.png');
        $('.robot-check-text').css('color','#26a69a');
    });
    
    if(!$('.robot-check').checked) {
        // alert("请勾选机器人验证后再发表评论！");
        $('.vsubmit').attr('disabled',true).attr('title','评论前勾选机器人验证按钮');
    } 
    $('.robot-check').on('click',function(){
        $('.vsubmit').attr('disabled',false).attr('title','欢迎畅所欲言');
    });
</script>

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6">
            <div class="article-badge left-badge text-color">
                <i class="far fa-dot-circle"></i>&nbsp;本篇
            </div>
            <div class="card">
                <a href="/posts/671b.html">
                    <div class="card-image">
                        
                        
                        <img src="/medias/banner/1.jpg" class="responsive-img" alt="R language learning Notes">
                        
                        <!-- 福袋按钮 -->
                        <div class="caishendeng">        
                            <div class="caishenxian wenzhangxian">
                                <img class="caishenpic lala" src="/medias/spring-img/fish.png" />
                            </div>              
                        </div>
                        <span class="card-title">
                          <!-- 文章卡片hover线条效果 -->
                          <span class="titlesline"></span>
                          R language learning Notes
                        </span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            《R语言数据分析从入门到进阶》是我在哔哩哔哩看的R语言教程，个人觉得很不错，所以把学习笔记分享出来，笔记来源：模型机器数据科学
1.入门知识
入门知识部分，主要介绍R语言相关软件安装与设置，相关资料网站，包的安装、加载、更新、移除等管理操作
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2023-05-30
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E7%94%B5%E8%84%91%E8%BD%AF%E4%BB%B6/" class="post-category">
                                    电脑软件
                                </a>
                            
                            
                        </span>
                    </div>
                </div>

                
                <div class="card-action article-tags">
                    
                    <a href="/tags/R/">
                        <span class="chip bg-color">R</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/posts/11c9.html">
                    <div class="card-image">
                        
                        
                        <img src="/medias/banner/3.jpg" class="responsive-img" alt="EndNote系列">
                        
                        <!-- 福袋按钮 -->
                        <div class="caishendeng">        
                            <div class="caishenxian wenzhangxian">
                                <img class="caishenpic lala" src="/medias/spring-img/fish.png" />
                            </div>              
                        </div>
                        <span class="card-title">
                          <!-- 文章卡片hover线条效果 -->
                          <span class="titlesline"></span>
                          EndNote系列
                        </span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            

                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2023-05-14
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E8%BD%AF%E4%BB%B6/" class="post-category">
                                    软件
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/EndNote/">
                        <span class="chip bg-color">EndNote</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>
<style>
  .articles .row .article {
    position: relative;
  }
</style>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('30')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: Oliver博客<br />'
            + '文章作者: Oliver博客<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->


        </div>
        
        
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        
        
        <div class="toc-widget" data-spmid="R">
            <div class="toc-title">
                <i class="far fa-list-alt"></i>
                &nbsp;&nbsp;目录
            </div>
            <div id="toc-content"></div>
        </div>
        
        
    </div>
</div>

<!-- TOC 悬浮按钮. -->

    
<div id="floating-toc-btn" class="hide-on-med-and-down" data-spmid="R">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>



<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    
</main>




    <style>
  footer {
    position: relative;
  }

  .page-footer {
    padding-top: 10px;
    padding-bottom: 10px;
  }
</style>
<footer class="page-footer bg-color">
  
  <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="hidess col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="3155294100"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='list'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
        <style>
            .hidess .aplayer-lrc {
                display: none!important;
            }
        </style>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

  

  <div class="container row center-align"
    style="margin-bottom: 15px !important;">
    <!-- 访客地图 -->
    <div class="col s12 m3 l3 social-link" id="visitmap">
      <a target="_blank" rel="noopener" href="https://clustrmaps.com/site/1bd51" title="访客地图"><img src="/medias/map-visit.png" /></a>
    </div>
    <!-- 版权信息 -->
    <div class="col s12 m6 l6 copy-right">
      Copyright&nbsp;&copy;
      <span id="year">2023</span>
      <a href="/about" target="_blank">Oliver博客</a>
      &nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
      &nbsp;
      <br>

      
      &nbsp;<i class="fas fa-chart-area"></i>&nbsp;Total number of words: &nbsp;<span
        class="white-color">3.7k</span>&nbsp;
      
      
      
      
      
      
      <span id="busuanzi_container_site_pv">
        <i class="far"></i>Total access: &nbsp;<span id="busuanzi_value_site_pv" class="white-color"></span>&nbsp;
      </span>
      
      
      <span id="busuanzi_container_site_uv">
        <i class="fas"></i>Total visits: &nbsp;<span id="busuanzi_value_site_uv" class="white-color"></span>&nbsp;
      </span>
      
      <br>
      
      <span id="sitetime">running time</span>
      <script>
        function siteTime() {
          var seconds = 1000;
          var minutes = seconds * 60;
          var hours = minutes * 60;
          var days = hours * 24;
          var years = days * 365;
          var today = new Date();
          var startYear = "2023";
          var startMonth = "3";
          var startDate = "9";
          var startHour = "0";
          var startMinute = "20";
          var startSecond = "0";
          var todayYear = today.getFullYear();
          var todayMonth = today.getMonth() + 1;
          var todayDate = today.getDate();
          var todayHour = today.getHours();
          var todayMinute = today.getMinutes();
          var todaySecond = today.getSeconds();
          var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
          var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
          var diff = t2 - t1;
          var diffYears = Math.floor(diff / years);
          var diffDays = Math.floor((diff / days) - diffYears * 365);
          var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
          var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
            minutes);
          var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
            diffMinutes * minutes) / seconds);
          if (startYear == todayYear) {
            document.getElementById("year").innerHTML = todayYear;
            document.getElementById("sitetime").innerHTML = "The site has been running for " +
              "<span class= 'white-color'>" + diffDays + "</span>" + " d " + "<span class= 'white-color'>" + diffHours +
              "</span>" +
              " h " + "<span class= 'white-color'>" + diffMinutes + "</span>" + " m " + "<span class= 'white-color'>" +
              diffSeconds + "</span>" + " s";
          } else {
            document.getElementById("year").innerHTML = startYear + " - " + todayYear;
            document.getElementById("sitetime").innerHTML = "The site has been running for " +
              "<span class= 'white-color'>" + diffYears + "</span>" + " y " + "<span class= 'white-color'>" + diffDays +
              "</span>" +
              " d " + "<span class= 'white-color'>" + diffHours + "</span>" + " h " + "<span class= 'white-color'>" +
              diffMinutes + "</span>" + " m " + "<span class= 'white-color'>" + diffSeconds + "</span>" + " s";
          }
        }
        setInterval(siteTime, 1000);
      </script>
      
      <br>
      
    </div>
    <div class="col s12 m3 l3 social-link social-statis">


    <a href="mailto:1952946598@qq.com" class="tooltipped" target="_blank" data-tooltip="nekodeng@qq.com" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>



    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1952946598" class="tooltipped" target="_blank" data-tooltip="1952946598" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>



</div>
  </div>
  <!-- 波浪条waveline -->
  <div class="wavelinefooter">
    <style>
      .wavelinefooter {
        background: url(/medias/wave.png) 0 0 repeat-x;
        height: 3px;
        width: 100%;
        position: absolute;
        left: 0;
        top: -3px;
        background-size: 10px 3px;
      }
    </style>
  </div>
</footer>

<!-- 底部进度条 -->
<div class="progress-bar" style="z-index: 999"></div>

    <!-- 搜索遮罩框 -->
<style>
#searchInput::-webkit-input-placeholder { /* WebKit browsers */ 
    font-size:16px;
} 
#searchInput:-moz-placeholder { /* Mozilla Firefox 4 to 18 */ 
    font-size:16px;
} 
#searchInput::-moz-placeholder { /* Mozilla Firefox 19+ */ 
    font-size:16px;
} 
#searchInput:-ms-input-placeholder { /* Internet Explorer 10+ */ 
    font-size:16px;
} 
#searchInput {
    margin-top: 6px;
    margin-bottom: 12px;
    text-indent: 4px;
    font-size: 14px;
}
</style>
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;站内搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input" autofocus="autofocus" />
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/search.xml", 'searchInput', 'searchResult');
});
</script>

<!-- 点击搜索按钮后input框自动获取焦点 -->


    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="javascript(0)">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>
    
    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

    <!--动态线条背景-->
    <script type="text/javascript" color="122 103 158" opacity='0.12' zIndex="-2" count="100" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js">
    </script>
 
    <script type="text/javascript" src="/js/click_show_text.js"></script>
    <script src="/js/linkcard.js"></script>

    <script src="/js/activate-power-mode.js"></script>
    <script>
        POWERMODE.colorful = true; // make power mode colorful
        POWERMODE.shake = false; // turn off shake
        document.body.addEventListener('input', POWERMODE);
    </script>

    <!-- 百度统计代码 -->
    <script>
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "";
          var s = document.getElementsByTagName("script")[0]; 
          s.parentNode.insertBefore(hm, s);
        })();
    </script>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

    <!----------节日判断,进行网站修饰，比如春节圣诞或变灰色的清明等----- -->
    <script>
        // 判断今天是哪个节假日或特殊纪念日进行网站修饰，比如春节圣诞或变灰色的清明等
        var curMonth = new Date().getMonth() + 1; //月
        var curDate = new Date().getDate(); //日
        function cancelguajian() {
            // 判断如果是变灰色的纪念日则将小挂件隐藏
            var guajianone = document.getElementsByClassName('caishendeng');
            var guajiantwo = document.getElementsByClassName('labelmz');
            var guajianthree = document.getElementsByClassName('friendmz');
            var denglong = document.getElementsByClassName('denglong');
            for(var i = 0; i < guajianone.length; i++) {
                guajianone[i].style.display = "none"
            };
            for(var j = 0; j < guajiantwo.length; j++) {
                guajiantwo[j].style.display = "none"
            }
            for(var k = 0; k < guajianthree.length; k++) {
                guajianthree[k].style.display = "none"
            };
            for(var x = 0; x < denglong.length; x++) {
                denglong[x].style.display = "none"
            };
            document.getElementById('switchchristmas').style.display = "none";
            document.getElementById('switchspring').style.display = "none";
            document.getElementById('xiaomaozitx').style.display = "none";
        }
        // --------------以下节日为公历，每年固定--------------
        if(curMonth == 1 && curDate == 1) {
            // 1月1日为元旦节
            document.body.classList.add('themespring');
            document.getElementById('dtone').innerHTML = "快乐";
            document.getElementById('dttwo').innerHTML = "元旦";
        }
        else if(curMonth == 9 && curDate == 29) {
            // 9月30日为全国烈士纪念日，设在国庆前一天
            document.getElementsByTagName('html')[0].classList.add('gray');
            document.getElementById('popupbb').style.display = "block";
            document.getElementById('jinianci').innerHTML = "今天是“ 9月30日 ”，“ 全国烈士纪念日 ”。定为每年的9月30日,正好是国庆前一天,让全国人民永远不要忘记先有无数先烈的前赴后继、奋勇献身,才有我们国家今天的繁荣富强、文明进步。"
            document.getElementById('switchchristmas').style.display = "none";
            document.getElementById('switchspring').style.display = "none";
            // document.body.classList.add('themespring');
            document.getElementById('dtone').innerHTML = "缅怀";
            document.getElementById('dttwo').innerHTML = "烈士";
            cancelguajian();
        }
        // 10月1日为国庆节
        else if(
          curMonth == 10 && curDate == 1
          || curMonth == 10 && curDate == 2
          || curMonth == 10 && curDate == 3
          || curMonth == 10 && curDate == 4
          || curMonth == 10 && curDate == 5
          || curMonth == 10 && curDate == 6
          || curMonth == 10 && curDate == 7) {
            document.body.classList.add('themespring');
            document.getElementById('dtone').innerHTML = "欢度";
            document.getElementById('dttwo').innerHTML = "国庆";
            document.getElementById('index-video').src = "https://txmov2.a.yximgs.com/upic/2021/09/30/15/BMjAyMTA5MzAxNTE5MDhfMTg1ODk2MDg4N181ODA5MjQ1NDkyMV8xXzM=_b_Bef514871cf947c46c11bc54a3ed3faa9.mp4?pkey=AAWo-kOQESq9j_AMCO-BT6jTPS090PuVHWtyuSQ8cddkgMmI3V-P9uWMDY13QrPuCjtWVbch_01wRcj6Rtm5w0AkLhgVTMSceLLiRYjlWUfLDNNLX3jISKEscl9uNXUnYcM&tag=1-1632986688-xpcwebprofile-0-ongrobirtl-58c917acab52d13f&clientCacheKey=3xajcj9u8fubzm4_b.mp4";
            document.getElementById('popupbb').style.display = "block"
            document.getElementById('tujis').style.display = "block";
            // document.getElementById('fights').style.display = "none";
            document.getElementById('jinianci').style.textAlign = "center";
            document.getElementById('jinianci').innerHTML = "《 国庆日🚩》<br> 十月惊雷震九重，国富民强聩耳聋。<br>城头城下聚农工，神州处处花潮涌。<br>而今白鹿奋清风，山长水远不知踪。"
          }
        else if(curMonth == 12 && curDate == 13) {
            // 12月13日为国家公祭日
            document.getElementsByTagName('html')[0].classList.add('gray');
            // document.body.classList.add('themespring');
            document.getElementById('dtone').innerHTML = "国家";
            document.getElementById('dttwo').innerHTML = "公祭";
            document.getElementById('jinianci').innerHTML = "今天是 “ 12月13日 ”，南京大屠杀死难者 “ 国家公祭日 ”。国行公祭，法立典章。铸兹宝鼎，祀我国殇。永矢弗谖，祈愿和平。中华圆梦，民族复兴。";
            document.getElementById('popupbb').style.display = "block";
            document.getElementById('switchchristmas').style.display = "none";
            document.getElementById('switchspring').style.display = "none";
            cancelguajian();
        }

        else if(curMonth == 5 && curDate == 22) {
            // 2021年5月22日袁隆平院士逝世，云南大理发生6级地震
            document.getElementsByTagName('html')[0].classList.add('gray');
            document.body.classList.add('dark');
            // document.body.classList.add('themespring');
            document.getElementById('dtone').innerHTML = "地震";
            document.getElementById('dttwo').innerHTML = "袁老";
            document.getElementById('jinianci').innerHTML = "今天是 “ 2021年5月22日 ”，杂交水稻之父、共和国勋章获得者袁隆平逝世，享年91岁，记忆中您还是小学课本里的爷爷形象，.......还有21日晚云南大理州遭受地震的大家，要好好地...";
            document.getElementById('popupbb').style.display = "block";
            document.getElementById('switchchristmas').style.display = "none";
            document.getElementById('switchspring').style.display = "none";
            cancelguajian();
        }

        else if(curMonth == 12 && curDate == 25) {
            // 12月25日为圣诞节
            document.body.classList.add('themechris');
        }
        // --------------以下节日为农历，每年不固定--------------
        else if(curMonth == 4 && curDate == 4) {
            // 2021年4月4日为清明节
            document.getElementsByTagName('html')[0].classList.add('gray');
            document.getElementById('switchchristmas').style.display = "none";
            document.getElementById('switchspring').style.display = "none";
            document.getElementById('popupbb').style.display = "block";
            document.getElementById('jinianci').innerHTML = "今天是“ 4月4日 ”，“ 清明节 ”，正是郊外踏青春游与行清墓祭的好时节。燕子来时新社,梨花落后清明。"
            // document.body.classList.add('themespring');
            document.getElementById('dtone').innerHTML = "安康";
            document.getElementById('dttwo').innerHTML = "清明";
            cancelguajian();
        }
        else if(curMonth == 1 && curDate == 31) {
            // 2021春节除夕为1月31日
            document.body.classList.add('themespring');
            document.getElementById('dtone').innerHTML = "快乐";
            document.getElementById('dttwo').innerHTML = "除夕";
        }
        else if(curMonth == 2) {
            // 2021春节为2月1日开始
            document.body.classList.add('themespring');
        }
        else if(curMonth == 6 && curDate == 14) {
            // 2021端午节为6月14日
            document.body.classList.add('themespring');
            document.getElementById('dtone').innerHTML = "安康";
            document.getElementById('dttwo').innerHTML = "端午";
        }
        else if(curMonth == 9 && curDate == 21) {
            // 2021中秋节为9月21日
            document.body.classList.add('themespring');
            document.getElementById('dtone').innerHTML = "团圆";
            document.getElementById('dttwo').innerHTML = "中秋";
        }
    </script>

    <!-- 实现tab切换点击标题显示下划线和颜色改变效果 -->
    <script>
        $(function () {
            var nowUrl = window.location.href
            var homeTab = $('nav ul li a[href="/"] span'),
                cateTab = $('nav ul li a[href="/categories"] span'),
                recordTab = $('nav ul li a[href="/record"] span'),
                tagsTab = $('nav ul li a[href="/tags"] span'),
                archivesTab = $('nav ul li a[href="/archives"] span'),
                countTab = $('nav ul li a[href="/count"] span'),
                aboutTab = $('nav ul li a[href="/about"] span'),
                videoTab = $('nav ul li a[href="/videos"] span'),
                musicTab = $('nav ul li a[href="/musics"] span'),
                galleryTab = $('nav ul li a[href="/gallery"] span'),
                essayTab = $('nav ul li a[href="/essay"] span'),
                booksTab = $('nav ul li a[href="/books"] span'),
                tiktokTab = $('nav ul li a[href="/tiktok"] span'),
                contactTab = $('nav ul li a[href="/contact"] span'),
                friendsTab = $('nav ul li a[href="/friends"] span'),
                collectionTab = $('nav ul li a[href="/collection"] span'),
                projectTab = $('nav ul li a[href="/project"] span'),
                donateTab = $('nav ul li a[href="/donate"] span'),
                olympusTab = $('nav ul li a[href="/olympus"] span'),
                lakersTab = $('nav ul li a[href="/lakers-championship"] span'),
                hotreviewTab = $('nav ul li a[href="/hotreview"] span'),
                ticktackTab = $('nav ul li a[href="/ticktack"] span'),
                friendcircleTab = $('nav ul li a[href="/friendcircle"] span'),
                chromedragonTab = $('nav ul li a[href="/chromedragon"] span'),
                voteTab = $('nav ul li a[href="/vote"] span'),
                // 获取二级菜单项
                achivesTab = $('nav .nav-menu .nav-item:nth-of-type(3) > a > span'),
                qingdanTab = $('nav .nav-menu .nav-item:nth-of-type(5) > a > span'),
                linksTab = $('nav .nav-menu .nav-item:nth-of-type(7) > a > span'),
                labTab = $('nav .nav-menu .nav-item:nth-of-type(8) > a > span');

            if(nowUrl.indexOf("categories") >= 0) {
                cateTab.addClass("aitems")
            } else if (nowUrl.indexOf("posts") >= 0) {
                homeTab.removeClass("aitems")
            } else if (nowUrl.indexOf("record") >= 0) {
                recordTab.addClass("aitems")
                achivesTab.addClass("erjiitems")
            } else if (nowUrl.indexOf("tags") >= 0) {
                tagsTab.addClass("aitems")
                achivesTab.addClass("erjiitems")
            } else if (nowUrl.indexOf("archives") >= 0) {
                archivesTab.addClass("aitems")
                achivesTab.addClass("erjiitems")
            } else if (nowUrl.indexOf("count") >= 0) {
                countTab.addClass("aitems")
                achivesTab.addClass("erjiitems")
            } else if (nowUrl.indexOf("videos") >= 0) {
                videoTab.addClass("aitems")
                qingdanTab.addClass("erjiitems")
            } else if (nowUrl.indexOf("musics") >= 0) {
                musicTab.addClass("aitems")
                qingdanTab.addClass("erjiitems")
            } else if (nowUrl.indexOf("gallery") >= 0) {
                galleryTab.addClass("aitems")
                qingdanTab.addClass("erjiitems")
            } else if (nowUrl.indexOf("essay") >= 0) {
                essayTab.addClass("aitems")
                qingdanTab.addClass("erjiitems")
            } else if (nowUrl.indexOf("books") >= 0) {
                booksTab.addClass("aitems")
                qingdanTab.addClass("erjiitems")
            } else if (nowUrl.indexOf("tiktok") >= 0) {
                tiktokTab.addClass("aitems")
                qingdanTab.addClass("erjiitems")
            } else if (nowUrl.indexOf("contact") >= 0) {
                contactTab.addClass("aitems")
            } else if (nowUrl.indexOf("about") >= 0) {
                aboutTab.addClass("aitems")
            } else if (nowUrl.indexOf("friends") >= 0) {
                friendsTab.addClass("aitems")
                linksTab.addClass("erjiitems")
            } else if (nowUrl.indexOf("collection") >= 0) {
                collectionTab.addClass("aitems")
                linksTab.addClass("erjiitems")
            } else if (nowUrl.indexOf("project") >= 0) {
                projectTab.addClass("aitems")
                linksTab.addClass("erjiitems")
            } else if (nowUrl.indexOf("donate") >= 0) {
                donateTab.addClass("aitems")
                linksTab.addClass("erjiitems")
            } else if (nowUrl.indexOf("olympus") >= 0) {
                olympusTab.addClass("aitems")
                linksTab.addClass("erjiitems")
            } else if (nowUrl.indexOf("lakers-championship") >= 0) {
                lakersTab.addClass("aitems")
                linksTab.addClass("erjiitems")
            } else if (nowUrl.indexOf("hotreview") >= 0) {
                hotreviewTab.addClass("aitems")
                labTab.addClass("erjiitems")
            } else if (nowUrl.indexOf("ticktack") >= 0) {
                ticktackTab.addClass("aitems")
                labTab.addClass("erjiitems")
            } else if (nowUrl.indexOf("friendcircle") >= 0) {
                friendcircleTab.addClass("aitems")
                labTab.addClass("erjiitems")
            } else if (nowUrl.indexOf("chromedragon") >= 0) {
                chromedragonTab.addClass("aitems")
                labTab.addClass("erjiitems")
            } else if (nowUrl.indexOf("vote") >= 0) {
                voteTab.addClass("aitems")
                labTab.addClass("erjiitems")
            } 
            else {
                homeTab.addClass("aitems")
            }
        });
    </script>
</body>
</html>
